<template>
	<view>
		<scroll-view class="my-tab" scroll-x :show-scrollbar="true" :scroll-with-animation="true" :scroll-left="scrollLeft">
			<view class="tab-wrapper">
				<view class="tab-list">
					<view class="tab-item" v-for="(item, index) in tabList" :key="index" :class="{active: currentIndex === index}"
						@tap="toggleTab(index)" :style="{width: 100 / pageNum + '%'}">{{item[keyName]}}</view>
				</view>
				<view class="active-line" :style="{left: currentIndex * leftStep + 'rpx', width: 100 / pageNum + '%'}">
					<view class="line"></view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: "my-tabs",
		props: {
			tabList: {
				default: []
			},
			keyName: { // 需要遍历的字段名
				default: 'name'
			},
			pageNum: {
				default: 5 // 一页显示几个 
			}
		},
		data() {
			return {
				currentIndex: 0,
				screenWidth: 750,
				leftStep: 0,	// 底部滑块单次移动距离
				scrollLeft: 0	// scroll-view移动总距离
			};
		},
		mounted(){
			this.leftStep = this.screenWidth / this.pageNum;
		},
		methods: {
			toggleTab(index) {
				this.currentIndex = index
				this.scrollLeft = uni.upx2px((index - 2)) * this.leftStep
				this.$emit('tabChange', this.tabList[index])
			},
		}
	}
</script>

<style lang="scss">
	.my-tab {
		position: sticky;
		display: flex;
		align-items: center;
		flex-direction: column;
		background: #FFFFFF;
		white-space: nowrap;

		.tab-wrapper {
			position: relative;
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 88rpx;
		}

		.tab-list {
			display: flex;
			width: 100%;
			height: 80rpx;
		}

		.tab-item {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-shrink: 0;
			font-size: 30rpx;
			font-weight: 500;
			color: #333333;
		}

		.active {
			font-size: 30rpx;
			font-weight: bold;
			color: $theme-color;
		}

		.active-line {
			position: absolute;
			left: 0;
			bottom: 0;
			display: flex;
			justify-content: center;
			transition: all .3s;
		}

		.line {
			width: 36rpx;
			height: 8rpx;
			background: $theme-color;
			border-radius: 4rpx;
		}
	}
</style>